package com.aigc.txt2img.controller.api;

import com.aigc.txt2img.entity.CreateImageReques;
import com.aigc.txt2img.entity.CreateImageResponse;
import com.aigc.txt2img.entity.NotifyRequest;
import com.aigc.txt2img.entity.QueryImageResponse;
import com.aigc.txt2img.exception.ExceptionEnum;
import com.aigc.txt2img.service.ChatService;
import com.aigc.txt2img.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/java_api/chat")
public class ChatController {

    @Autowired
    ChatService chatService;

    @RequestMapping(value = "/create/image", method = RequestMethod.POST)
    public ResponseUtil createImage(@RequestBody @Validated CreateImageReques createImage) throws Exception {

        System.out.println("createImage :" + createImage);
        String data = chatService.createImage(createImage);
        if (data != "") {
            CreateImageResponse ret = new CreateImageResponse();
            ret.setId(data);
            //            Map<String, String> ret = new HashMap<>();
            //            data.put("id", data);
            return ResponseUtil.success(data);
        }
        return ResponseUtil.error(ExceptionEnum.SERVER_BUSY);
    }

    @RequestMapping(value = "/query/image", method = RequestMethod.GET)
    public ResponseUtil queryImage(@RequestParam("task_id") String taskId) {

        log.debug("taskId:" + taskId);
        if (taskId == "") {
            return ResponseUtil.error(ExceptionEnum.CLIENT_PARAMS_INVALID);
        }
        QueryImageResponse ret = new QueryImageResponse();

        try {
            String data = chatService.queryImage(taskId);
            log.debug("data:" + data);
            ret.setImage(data);
            return ResponseUtil.success(ret);
        } catch (Exception e) {
            return ResponseUtil.error(ExceptionEnum.SERVER_BUSY);
        }
    }

    @RequestMapping(value = "/net_ease/notify", method = RequestMethod.POST)
    public ResponseEntity<ResponseUtil> notify(@RequestBody @Validated NotifyRequest notify) {

        ResponseUtil res = new ResponseUtil();
        res.setData(notify);
        try {
            String taskId = notify.getRequestId();
            String image = notify.getImage();
            if (taskId == "" || chatService.notify(taskId, image)) {
                return new ResponseEntity<ResponseUtil>(res, HttpStatus.OK);
            }
        } catch (Exception e) {
            log.error("e:" + e.toString());
        }
        return new ResponseEntity<ResponseUtil>(res, HttpStatus.INTERNAL_SERVER_ERROR);
    }

}